package com.security.manage.apigateway.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class ResponseFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpResponse originalResponse = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();
        if (uri.indexOf("/login")>0||uri.indexOf("/v2/api-docs")>0){
            return chain.filter(exchange);
        }

        String refreshToken = request.getHeaders().getFirst("refreshToken");
        if (StringUtils.isNotEmpty(refreshToken)) {
            originalResponse.getHeaders().add("token", refreshToken);
        }

        return chain.filter(exchange.mutate().response(originalResponse).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
